/**
 * 同步上菜状态接口
 */

//引入Q模块
let Q = require('q');

let index = function(getData, postData, config, _redis, db) {
	let deferred = Q.defer();
	if(postData.orderId && postData.foodId && postData.timestamp) {
		db.select('storeOrder', {
			orderId: postData.orderId
		}).then(function(orderData) {
			if(orderData.length > 0) {
				let goodsList = orderData[0].goodsList;
				for(let foodIndex in goodsList) {
					if(goodsList[foodIndex].foodId == postData.foodId) {
						if(goodsList[foodIndex].serving != postData.serving) {
							goodsList[foodIndex].serving = postData.serving;
							return db.update('storeOrder', {
								orderId: postData.orderId
							}, {
								goodsList: goodsList
							});
						}
						else {
							deferred.resolve(true);
							return deferred.promise;
						}
						break;
					}
					if(foodIndex == goodsList.length - 1) {
						//同步上菜状态接口对应的订单中找不到需要操作的菜品
						deferred.reject('-0116');
					}
				}
			}
			else {
				//同步上菜状态接口查找不到对应订单
				deferred.reject('-0115');
			}
		}, function() {
			//同步上菜状态接口查询订单信息时出错
			deferred.reject('-0114');
		}).then(function() {
			deferred.resolve(['broadcast', {
				storeId: postData.storeId,
				type: 'sys',
				event: 'orderServingChange',
				data: {
					orderId: postData.orderId,
					foodId: postData.foodId,
					serving: postData.serving,
					timestamp: postData.timestamp
				}
			}]);
		}, function() {
			//同步上菜状态接口更新上菜状态到数据库失败
			deferred.reject('-0117');
		});
	}
	else {
		//同步上菜状态接口参数不足
		deferred.reject('-0113');
	}
	return deferred.promise;
}

module.exports = {
	index: index
};